/**
 * Created by levy on 16/6/15.
 */
/**
 * 选择组件, option 由 ajax 获取
 * 传参:
 *
 * addClass: add more class to this select
 * name: name 与 id 都叫这个
 * groupCode: 有值则查询从数据字典
 * api:
 * text:
 * value:
 */
var Select = React.createClass({
    getInitialState() {
        return {
            options: [],
            value: '',
            hasReceived: false,
        }
    },
    componentDidMount() {
        liefeng.utils.ajax({
            data: {
                groupCode: this.props.groupCode,
            }
        }, liefeng.api.dictList, function (data) {
            var optionList = data.map(function (data) {
                return <option value={data.value}>{data.name}</option>
            });

            this.setState({options: optionList});
        }.bind(this))
    },
    render() {
        var props = this.props,
            value = this.state.value;

        return(
            <select ref="lfSelect" className={'lf-select ' + (props.addClass || '')}
                    name={props.name} id={props.name}  value={value} disabled={props.disabled}
                    onChange={this._onChange}>
                {this.state.options}
            </select>
        )
    },
    componentWillReceiveProps(nextProps) {
        if(!nextProps.value || this.state.hasReceived)  return;

        this.setState({value: nextProps.value, hasReceived: true});
    },
    _onChange() {
        var value = React.findDOMNode(this.refs.lfSelect).value;

        this.setState({value: value});
    }
});

export default Select;